﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using myBoard.Framework;
using System.Reflection;
using System.Globalization;
using System.Windows.Threading;

namespace MagnetHost
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main : Window
    {
        private MagnetEx _magnet = null;
        private DispatcherTimer _saveStateTimer = null;
        private string _appFolder;

        public Main()
        {
            InitializeComponent();
            _magnet = GetMagnet();

            if (_magnet != null)
            {
                _magnetContainer.Child = _magnet.Magnet as UserControl;
                this.Title = _magnet.MagnetName;
                if (_magnet.Magnet is IRequiresStorage)
                {
                    Storage storage = new Storage();
                    string storagePath = System.IO.Path.Combine(_appFolder, "Storage");
                    if (!Directory.Exists(storagePath))
                        Directory.CreateDirectory(storagePath);
                    DirectoryInfo di = new DirectoryInfo(storagePath);
                    storage.StorageDirectory = di;
                    ((IRequiresStorage)_magnet.Magnet).GetStorage(storage);
                }


                this.MouseLeftButtonDown += new MouseButtonEventHandler(Main_MouseLeftButtonDown);
                _closeBt.Click += new RoutedEventHandler(_closeBt_Click);
                _minimizeBt.Click += new RoutedEventHandler(_minimizeBt_Click);

                _saveStateTimer = new DispatcherTimer();
                _saveStateTimer.Interval = new TimeSpan(0, 0, 5);
                _saveStateTimer.Tick += new EventHandler(_saveStateTimer_Tick);
                _saveStateTimer.Start();

                this.StateChanged += new EventHandler(Main_StateChanged);
            }
            else
            {
                this.Close();
            }
        }

        void Main_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
                this.ShowInTaskbar = true;
            else
                this.ShowInTaskbar = false;
        }

        void _saveStateTimer_Tick(object sender, EventArgs e)
        {
            _magnet.SaveState();
        }

        void _minimizeBt_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        void _closeBt_Click(object sender, RoutedEventArgs e)
        {
            _magnet.SaveState();
            _magnet.Terminate();
            this.Close();
        }

        void Main_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private MagnetEx GetMagnet()
        {
            _appFolder = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo di = new DirectoryInfo(_appFolder);
            FileInfo[] dlls = di.GetFiles("*.dll");

            try
            {
                List<MagnetEx> list = new List<MagnetEx>();
                foreach (FileInfo dll in dlls)
                {
                    if (!dll.FullName.Contains("myBoard.Framework.dll"))
                    {
                        try
                        {
                            Assembly assembly = Assembly.LoadFile(dll.FullName);
                            Type[] types = assembly.GetTypes();
                            foreach (Type type in types)
                            {
                                if (type.GetInterface("IMagnet") != null)
                                {
                                    IMagnet magnet = assembly.CreateInstance(type.FullName, false, BindingFlags.CreateInstance, null, null, CultureInfo.InstalledUICulture, null) as IMagnet;
                                    if (magnet != null)
                                    {
                                        MagnetEx item = new MagnetEx(magnet)
                                        {
                                            FullyQualifiedName = dll.FullName
                                        };
                                        return item;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ExceptionsManager.LogException("MagnetHost", string.Format("Could not load magnet {0}", dll.Name), ex, System.Diagnostics.EventLogEntryType.Error, true);
                        }
                    }
                }
                return null;
            }
            catch (Exception exception)
            {
                ExceptionsManager.LogException("MagnetHost", exception, true);
                return null;
            }
        
        }
    }
}
